package com.entor.hqj.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by hqj on 2018/1/23 0023.
 * 发送Http请求，获取Controller返回的数据
 */

public class HttpPostUtils {
    public static String doPostRequest(String path,Object connet){
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try{
            System.out.println("要发送的信息是"+connet);
            /*拼接url,Android这里需要换上远程地址，
            因为Android端没办法访问localhost,所以用ip，java的话本地tomcat运行的话倒是无妨*/
            // TODO: 2018/1/23 链接地址
            String address = "http://192.168.1.101:8080/login/"+path+"?"+connet;
            URL url = new URL(address);
            HttpURLConnection httpURLConnection =
                    (HttpURLConnection)url.openConnection();
            //这两个参数必须添加
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            //设置超时时间
            httpURLConnection.setReadTimeout(10*1000);
            httpURLConnection.setConnectTimeout(10*1000);
            //提交方式
            httpURLConnection.setRequestMethod("POST");
            //防止出现EOFException错误
            httpURLConnection.addRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");



            httpURLConnection.connect();
            //在输入流中写入参数
            out = new PrintWriter(httpURLConnection.getOutputStream());
            out.flush();
            //判断链接状态码
            if(httpURLConnection.getResponseCode()==200){
                in = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream())
                );
                String line = "";//防止出现null
                while ((line=in.readLine())!=null){
                    result += line;
                }
            }
            out.close();
            in.close();
            System.out.println("服务器返回的结果是"+result);
            //截取,从第一个出现{的地方开始，到结束位置
            //result = result.substring(result.indexOf("{"));
            return result;

        }catch (MalformedURLException e){
            System.out.println("URL异常");
            e.printStackTrace();
        }catch (IOException e){
            System.out.println("io异常");
            e.printStackTrace();
        }finally {

        }

        return "";
    }
}
